# -*- coding: utf-8 -*-
import os
import sys
import re
import requests
from bs4 import BeautifulSoup
import json

# '${dd}'
pwd = os.path.dirname(os.path.dirname(__file__))
import pandas as pd

sys.path.insert(0, '/web')
# 进入django设置
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'shop.settings')

import django

django.setup()

from goods.models import Product, Good


# for item in Product.objects.all():
#     child = [x.sold_price for x in item.goods.all()]
#     if len(child) == 1:
#         max_price = child[0]
#         min_price = child[0]
#     else:
#         max_price = max(child)
#         min_price = min(child)
#
#     item.min_price = min_price
#     item.max_price = max_price
#     item.save()

def geturl(filename):
    url = 'https://www.oschina.net/question/ckeditor_dialog_img_upload'
    headers = {
        "Host": "www.oschina.net",
        "Referer": "https://www.oschina.net/question/ask",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36",
        "Cookie": "__gads=ID=f5b00f1e4d17dc7b:T=1585900539:S=ALNI_MbQ8bB61a22zBX48VoN0qBUxQk7-Q; _user_behavior_=ecf5299b-32d4-49b5-81ab-abd857ab4c92; _reg_key_=w0eIoknWD5iFZr4tSGRk; yp_riddler_id=0e3792f3-03af-4f7b-8677-f6f195cdbad3; socialauth_id=RAg02HShkLqCPO8Lm433; _openid_key_=9a73e60f-2655-4795-8117-47e0906c37f3; Hm_lvt_a411c4d1664dd70048ee98afe7b28f0b=1593186715,1593187916,1593188000,1593188240; oscid=VEyPzQk6uUK1f61ugpczu37cWOooJrmzxI%2BoKvWSzxLlh6GBWKcMuo3KyuBI8Dq%2Bak1IYv2da%2FsGnQAGdLb0u%2Fzm2JkykyHjd8ZbQbU6WAvrGNOHKd%2F%2Blbx2D1kVhY7Ra4cH6mU1ZtM%3D; OSCHINA_SESSION=2625F8C96CFEA366241DBE80F45AA50F; ckCsrfToken=8pBPFKB5Wa6F2fJbaw7rWiyfzu5tJ2WC6GylAlL7; Hm_lpvt_a411c4d1664dd70048ee98afe7b28f0b=1593188414"
    }
    file = {'upload': (
        'test.png', requests.get(filename).content, 'image/png')}

    rep = requests.post(url, files=file, headers=headers)
    print(rep.json())
    return rep.json()['url']


def image(url):
    # url = 'https://www.cosme-de.net/pd/products/LXB0008?product_no=LXB0008'
    cont = requests.get(url).content.decode()
    con = re.findall('<script type="application/ld\+json">(.+?)</script>', cont, re.S | re.M)[-1]

    res = json.loads(con, strict=False)[0]

    price = res['offers']['price']
    status = res['offers']['availability']
    image = res['image']
    print(price, status, image)
    return price, status, image


def loop1():
    for item in Product.objects.all():
        try:
            source_url = item.source_url
            print(source_url)
            price, status, image_url = image(source_url)

            # print(source_url)
            json_image = json.dumps([geturl(image_url)])
            # print(json_image)
            item.images = json_image

        except Exception as e:
            print(e)
            good = item.goods.all()[0]
            item.images = good.images

        # item.save()


def loop2():
    for item in Good.objects.all():
        try:
            source_url = item.source_url
            price, status, image_url = image(source_url)
            curl = geturl(image_url)

            item.cover = curl
            item.third_price = price
            cs = 1 if status == 'InStock' else 0
            item.is_sold = cs

            print(cs, price, curl)

        except:

            item.cover = json.loads(item.images)[0]
            item.is_sold = 1
            item.third_price = item.sold_price

        item.save()


if __name__ == '__main__':
    loop1()
    # loop2()

# docker run --name nginx -p 80:80 -v /home/docker-nginx/nginx.conf:/etc/nginx/nginx.conf   -d nginx